package com.rex.aop;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created by frt on 2017/11/3.
 * 切面 AOP
 */
@Aspect
@Component
public class WebLogAspect {
    private Logger logger = Logger.getLogger(WebLogAspect.class);

    @Pointcut("execution(public * com.rex.web..*.*(..))")
    public void webLog(){

    }

    /**
     * 在 webLog() 前执行
     * @param joinPoint
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        logger.info("URI:" + request.getRequestURI());
        logger.info("HTTP_METHOD:" + request.getMethod());
        logger.info("IP:" + request.getRemoteAddr());
        logger.info("CLASS_METHOD:" + joinPoint.getSignature().getDeclaringTypeName());
        logger.info("ARGS:" + Arrays.toString(joinPoint.getArgs()));
    }

    /**
     * 在 webLog() return 后执行
     * @param ret
     */
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret){
        logger.info("RESPONSE:" + ret);
    }
}
